<template>
  <el-dialog
    :visible.sync="dialogVisible"
    :title="title"
    width="600px"
    :close-on-click-modal="false"
    @close="close"
  >
    <el-form ref="form" v-loading="loading" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="所属门店：" prop="shopId">
        <el-select v-model="form.shopId" placeholder="请选择" :disabled="isSync">
          <el-option
            v-for="item in $store.state.user.manageShopList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="名称：" prop="name">
        <el-input v-model="form.name" placeholder="请输入名称" :disabled="isSync" />
      </el-form-item>

      <el-form-item label="手机号：" prop="mobilePhone">
        <el-input v-model="form.mobilePhone" placeholder="请输入手机号" :maxlength="11" :disabled="!userId && isSync" />
      </el-form-item>

      <el-form-item label="登录账号：" prop="username">
        <el-input type="password" style="display:none" />
        <el-input v-model="form.username" placeholder="请输入登录账号" auto-complete="new-password" :disabled="isSync">
          <template slot="append">@{{ userSuffix }}</template>
        </el-input>
      </el-form-item>

      <el-form-item v-if="mode === 'add'" label="密码：" prop="password" >
        <el-input type="password" style="display:none" />
        <el-input
          v-model="form.password"
          type="password"
          placeholder="请输入密码"
          auto-complete="new-password"
          :disabled="!userId && isSync"
        />
      </el-form-item>

      <el-form-item label="选择角色：" prop="roles">
        <el-select v-model="form.roles" style="width: 100%" multiple placeholder="请选择" :disabled="!userId && isSync">
          <el-option v-for="item in roles" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="备注：" prop="description">
        <el-input v-model="form.description" maxlength="30" placeholder="说明备注" :disabled="!userId && isSync" />
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button size="small" round @click="hide">取 消</el-button>
      <el-button size="small" round type="primary" @click="handleSubmit('form')" :style="!userId && isSync ? 'background: #ccc; border-color: #ccc' : ''">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  validateLoginPw,
  validateLoginId,
  validateStrLen,
  validateMobilePhone
} from '@/utils/validate.js'
import { addUser, updateUser, getUser } from '@/api/user'
import { allRole } from '@/api/role'

export default {
  props: {
    scope: {
      require: true,
      type: Number
    },
    shopId: {
      require: true,
      type: Number
    }
  },
  data() {
    // 名称
    const validateName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入用户名'))
      } else if (!validateStrLen(value, 30)) {
        callback(new Error('长度不超过15个汉字或30个字符'))
      } else {
        callback()
      }
    }
    // 登录名
    const validateUserName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入登录名'))
      } else if (!validateLoginId(value)) {
        callback(new Error('长度不超过12位英文数字'))
      } else {
        callback()
      }
    }
    // 密码
    const validatePassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else if (!validateLoginPw(value)) {
        callback(new Error('长度为6~12个字符,支持数字,大小写字母'))
      } else {
        callback()
      }
    }
    // 手机号
    const validateTelPhone = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入手机号码'))
      } else if (!validateMobilePhone(value)) {
        callback(new Error('请输入正确手机号'))
      } else {
        callback()
      }
    }
    return {
      rules: {
        shopId: [
          {
            required: true,
            message: '请选择组织架构',
            trigger: ['change']
          }
        ],
        name: [
          {
            required: true,
            validator: validateName,
            trigger: ['blur', 'change']
          }
        ],
        password: [
          {
            required: true,
            validator: validatePassword,
            trigger: ['blur', 'change']
          }
        ],
        mobilePhone: [
          {
            required: true,
            validator: validateTelPhone,
            trigger: ['blur', 'change']
          }
        ],
        username: [
          {
            required: true,
            validator: validateUserName,
            trigger: ['blur', 'change']
          }
        ],
        roles: [
          {
            required: true,
            message: '请选择角色',
            trigger: ['blur', 'change']
          }
        ],
        description: [
          {
            message: '请输入',
            trigger: 'blur'
          }
        ]
      },
      isSync: false,
      title: null,
      resolve: null,
      loading: false,
      reject: null,
      mode: null,
      userId: null,
      dialogVisible: null,
      roles: [],
      form: {
        shopId: '',
        username: '',
        password: '',
        mobilePhone: '',
        name: '',
        sex: 2,
        roles: [],
        description: ''
      }
    }
  },
  computed: {
    ...mapGetters(['userSuffix', 'userInfo'])
  },
  mounted() {
    this.isSync = !!this.userInfo.business.syncTmpMerchantId
  },
  methods: {
    fetchData() {
      this.loading = true
      return getUser(this.userId)
        .then(res => {
          this.loading = false
          if (res.code === 0) {
            const oRoles = res.data.roles
            const roles = []
            for (let i = 0; i < oRoles.length; i++) {
              roles.push(oRoles[i].id)
            }
            res.data.roles = roles
            this.form = res.data
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(() => {
          this.loading = false
        })
    },

    openAdd() {
      this.mode = 'add'
      this.title = '新增员工'
      this.userId = null
      this.form.shopId = this.shopId !== -1 ? this.shopId : 0
      // 拉取所有用户
      allRole(this.scope)
        .then(res => {
          this.roles = res.data
        })
        .catch(() => {})
      this.show()
      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },

    openEdit(userId) {
      this.title = '编辑员工'
      this.mode = 'edit'
      this.userId = userId
      allRole(this.scope).then(res => {
        this.roles = res.data
      })
      this.fetchData()
      this.show()
      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },

    close() {
      this.loading = false
      this.form = {
        shopId: '',
        username: '',
        password: '',
        mobilePhone: '',
        name: '',
        sex: 2,
        roles: [],
        description: ''
      }
      this.$refs.form.resetFields()
    },

    show() {
      this.dialogVisible = true
    },

    hide(formName) {
      this.resolve = null
      this.reject = null
      this.dialogVisible = false
    },

    handleParentIdChange(value) {
      if (value && value.length > 0) {
        this.form.parentId = value[value.length - 1]
      } else {
        this.form.parentId = -1
      }
    },

    updateObject() {
      const data = Object.assign({}, this.form)
      const roles = data.roles
      const newRoles = []
      for (let i = 0; i < roles.length; i++) {
        newRoles.push({ id: roles[i] })
      }
      this.loading = true
      data.roles = newRoles
      return updateUser(this.userId, data, this.scope)
        .then(res => {
          this.loading = false
          if (res.code === 0) {
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000,
              offset: 40
            })
            this.resolve && this.resolve()
            this.hide()
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(() => {
          this.loading = false
        })
    },

    addObject() {
      if (!this.form.parentId) {
        this.form.parentId = -1
      }
      const data = Object.assign({}, this.form)
      const roles = data.roles
      const newRoles = []
      for (let i = 0; i < roles.length; i++) {
        newRoles.push({ id: roles[i] })
      }
      this.loading = true
      data.roles = newRoles
      return addUser(data, this.scope)
        .then(res => {
          this.loading = false
          if (res.code === 0) {
            this.$notify({
              title: '成功',
              message: '添加成功',
              type: 'success',
              duration: 2000,
              offset: 40
            })
            this.resolve && this.resolve()
            this.hide()
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(() => {
          this.loading = false
        })
    },

    handleSubmit(formName) {
      if(!this.userId && this.isSync) return
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.mode === 'edit') {
            this.updateObject()
          } else {
            this.addObject()
          }
        }
      })
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  .el-select {
    width: 100%;
  }
</style>
